<template>
  <div class="wrap" v-loading="loading">
    <div class="content" >
      <div class="step-content" v-show="step === 1">
        <h4>1.{{ $t('transfer.按店铺选择调货的商品和数量') }}</h4>
        <div>
          <el-button class="mgb10" size="medium" :type="currentForm.type === 1 ? 'primary' : ''" @click="changeType(1)" >
            暂存转代发
          </el-button>
          <el-button class="mgb10" size="medium" :type="currentForm.type === 2 ? 'primary' : ''" @click="changeType(2)" >
            代发转暂存
          </el-button>
        </div>

        <div class="account-list" v-if="currentAccountList.length > 1">
          <el-button
            class="mgb10"
            v-for="account in currentAccountList"
            size="medium"
            :key="account.accountId"
            :type="currentForm.ogAccountId === account.accountId ? 'primary' : ''"
            @click="chooseAccount(account)"
          >{{account.showName}}</el-button>
        </div>

        <div>
          <div>
            <div class="step-tips">
              <div style="display: inline;font-size: 14px">
                <div class="mgr10" style="display: inline-block">
                  {{$t('shipment.step2Tips4')}}：<span class="font-blue">{{currentSkuNum}}</span>
                </div>
                <div style="display: inline-block">
                  {{$t('shipment.step2Tips5')}}：<span class="font-blue">{{currentGoodsNum}}</span>
                </div>
              </div>

            </div>
            <div class="search mgt20">
              <el-input
                v-model="goodsParams.keyword"
                :placeholder="$t('common.searchForCompleteListingIDorSKU')"
                style="width: 250px; margin-right: 10px; margin-bottom: 10px"
                @keyup.enter.native="searchGoods()"
                clearable
                @clear="searchGoods()"
              >
              </el-input>
              <el-button class="mgr10" size="small" type="primary" @click="searchGoods()">{{$t('common.search')}}</el-button>

            </div>
          </div>
        </div>

        <div class="goods-table" >
          <el-table
            border
            :data="goodsList"
            v-loading="goodsLoading"
            v-tableHeight="{bottomOffset: 80}"
            height="100px"
            ref="goodsTableDataOne"
          >
            <el-table-column
              :label="$t('table.productCover')"
              align="center"
              width="120"
              fixed="left"
            >
              <template slot-scope="{row}">
                <div class="img-box img-one">
                  <img :src="row.image" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.title')"
              align="left"
              min-width="300"
            >
              <template slot-scope="{row}">
                {{row.title}}
                <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.当前店铺的Listing ID与SKU')"
              align="left"
              min-width="300"
            >
              <template slot-scope="{row}">
                {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
              </template>
            </el-table-column>
            <m-l-code-column></m-l-code-column>
            <template v-if="currentForm.type === 2">
              <el-table-column
                :label="$t('table.当前店铺中转送仓库存')"
                align="center"
                width="200"
                prop="middleStockNum"
              >
              </el-table-column>
            </template>
            <template v-if="currentForm.type === 1">
              <el-table-column
                :label="$t('table.当前店铺一件代发库存')"
                align="center"
                width="200"
                prop="stockNum"
              >
              </el-table-column>
            </template>

            <el-table-column
              :label="$t('table.当前商品可调货库存')"
              align="center"
              width="200"
              prop="transferNum"
            >
            </el-table-column>
            <el-table-column
              :label="$t('table.operate')"
              align="center"
              width="200"
              prop="currentMiddleNum"
              fixed="right"
            >
              <template v-slot="{row}">
                <el-button
                  :type="isInEditGoodsList(row) ? 'warning' : 'primary'"
                  @click="editTransferNum(row)"
                >
                  {{isInEditGoodsList(row) ? $t('middle.修改调货库存') : $t('transfer.确认调货库存')}}
                </el-button>
              </template>
            </el-table-column>

          </el-table>

          <!-- 仓库商品 -->

          <div class="page-wrap">
            <el-pagination
              background
              layout="total, prev, pager, next, jumper"
              :current-page.sync="goodsParams.page"
              :page-size="goodsParams.pageSize"
              :total="total"
              @current-change="getGoods"
            >
            </el-pagination>
          </div>
        </div>

        <div class="step-tips" v-if="false">
          {{$t('transfer.请选择那个店铺商品需要调入库存')}}
        </div>
      </div>


      <div class="step-content" v-show="step === 2" v-loading="calLoading">
        <h4>2.{{ $t('transfer.确认本次调货商品和数量') }}</h4>
        <div>
          <el-card class="box-card">
            <div class="line">
              <div class="label">{{ $t('table.store') }}：</div>
              <div class="item">{{ account.showName }}</div>
            </div>
            <div class="line">
              <div class="label">{{ $t('table.调货类型') }}：</div>
              <div class="item">{{ getTransferTypeStr(currentForm.type) }} </div>
            </div>
            <div class="line">
              <div class="label">{{$t('table.箱子数量')}}：</div>
              <div class="item">{{currentBoxNum}}</div>
              <div class="label mgl20">{{ $t('table.调货SKU种类数') }}：</div>
              <div class="item">{{ currentSkuNum }}</div>
              <div class="label mgl20">{{ $t('table.调货总数量') }}：</div>
              <div class="item">{{ currentGoodsNum }}</div>
            </div>
            <div class="line">
              <div class="label">{{ $t('table.预计调货费用（元）') }}：</div>
              <div class="item">{{ calTransferFee }}</div>
              <div class="label mgl20">{{ $t('table.预计贴标费用（元）') }}：</div>
              <div class="item">{{ calLabelFee}}</div>
            </div>
            <div class="line">
              <div class="label">{{ $t('table.预计总费用（元）') }}：</div>
              <div class="item">{{ exTotalFee }}</div>
            </div>
          </el-card>
        </div>

        <div class="goods-table">
          <div v-if="straightGoodsListV2.length > 0">
            <h4>{{ $t('transfer.无需贴标调货商品详细情况') }}：</h4>
            <el-table
              :data="straightGoodsListV2"
              row-key="id"
              border
              style="width: 1500px"
              v-tableHeight="{bottomOffset: 80}"
              height="100px"
              ref="goodsTableDataTwo"
            >
              <el-table-column
                :label="$t('table.productCover')"
                align="center"
                width="120"
                fixed="left"
              >
                <template slot-scope="{row}">
                  <div class="img-box img-one">
                    <img :src="row.image" alt="">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.title')"
                align="left"
                min-width="300"
              >
                <template slot-scope="{row}">
                  {{row.title}}
                  <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="当前店铺Listing ID与SKU"
                align="left"
                min-width="300"
              >
                <template slot-scope="{row}">
                  {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
                </template>
              </el-table-column>
              <m-l-code-column></m-l-code-column>
              <template v-if="currentForm.type === 1">
                <el-table-column
                  :label="$t('table.当前店铺一件代发库存')"
                  align="center"
                  width="150"
                  prop="stockNum"
                >
                </el-table-column>
              </template>
              <template v-else-if="currentForm.type === 2">
                <el-table-column
                  :label="$t('table.当前店铺中转送仓库存')"
                  align="center"
                  width="150"
                  prop="middleStockNum"
                >
                </el-table-column>
              </template>

              <el-table-column
                :label="$t('table.调出店铺Listing ID与SKU')"
                align="left"
                min-width="300"
                v-if="false"
              >
                <template slot-scope="{row}">
                  <template v-if="row.fromIsSystemLabel">
                    {{$t('shipment.System label')}} ({{row.fromSku}})
                  </template>
                  <template v-else-if="row.fromIsTB">
                    {{$t('shipment.Not labeled')}}
                  </template>
                  <template v-else>
                    {{row.fromGoodsId}}{{row.fromSku ? `(${row.fromSku})` : ''}}
                  </template>
                </template>
              </el-table-column>


              <template v-if="currentForm.type === 1">
                <el-table-column
                  :label="$t('table.预计从中转送仓调出')"
                  align="center"
                  width="150"
                  prop="transferMiddleStockNum"
                >
                  <template v-slot="{row}">
                    <template v-if="row.middleBoxInfo.length === 0">
                      -
                    </template>
                    <div
                      v-for="(item,index) in row.middleBoxInfo"
                      :key="index"
                    >
                      {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                    </div>
                  </template>
                </el-table-column>
              </template>
              <template v-else-if="currentForm.type === 2">
                <el-table-column
                  :label="$t('table.预计从一件代发调出')"
                  align="center"
                  width="150"
                  prop="transferStockNum"
                >
                  <template v-slot="{row}">
                    <template v-if="row.stockBoxInfo.length === 0">
                      -
                    </template>
                    <div
                      v-for="(item,index) in row.stockBoxInfo"
                      :key="index"
                    >
                      {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                    </div>
                  </template>
                </el-table-column>
              </template>
              <el-table-column
                :label="$t('table.预计调入商品总数量')"
                align="center"
                width="200"
                prop="exTotalGoodsNum"
              >
                <template v-slot="{row}">
                  <template v-if="currentForm.type === 1">
                    {{calGoodsNum(row.middleBoxInfo)}}
                  </template>
                  <template v-else>
                    {{calGoodsNum(row.middleBoxInfo) + calGoodsNum(row.stockBoxInfo)}}
                  </template>
                </template>
              </el-table-column>


            </el-table>
          </div>

          <div v-if="distributionGoodsListV2.length > 0">
            <h4>{{ $t('transfer.需贴标调货商品详细情况') }}：</h4>
            <el-table
              :data="distributionGoodsListV2"
              border
              :span-method="objectSpanMethod1"
              v-tableHeight="{bottomOffset: 80}"
              height="100px"
              ref="goodsTableDataThree"
            >
              <el-table-column
                :label="$t('table.productCover')"
                align="center"
                width="120"
                fixed="left"
                prop="image"
              >
                <template slot-scope="{row}">
                  <div class="img-box img-one">
                    <img :src="row.image" alt="">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.title')"
                align="left"
                min-width="300"
                prop="title"
              >
                <template slot-scope="{row}">
                  {{row.title}}
                  <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.当前店铺的Listing ID与SKU')"
                align="left"
                min-width="300"
                prop="goodsId"
              >
                <template slot-scope="{row}">
                  {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
                </template>
              </el-table-column>
              <m-l-code-column></m-l-code-column>
              <template v-if="currentForm.type === 1">
                <el-table-column
                  :label="$t('table.当前店铺一件代发库存')"
                  align="center"
                  width="200"
                  prop="stockNum"
                >
                </el-table-column>
              </template>
              <template v-else-if="currentForm.type === 2">
                <el-table-column
                  :label="$t('table.当前店铺中转送仓库存')"
                  align="center"
                  width="200"
                  prop="middleStockNum"
                >
                </el-table-column>
              </template>

              <el-table-column
                :label="$t('table.调出店铺Listing ID与SKU')"
                align="left"
                min-width="300"
                prop="fromGoodsId"
              >
                <template slot-scope="{row}">
                  <template v-if="row.fromIsTB">
                    {{ $t('shipment.Not labeled') }}
                  </template>
                  <template v-else-if="row.fromIsSystemLabel">
                    {{ $t('shipment.System label') }} ({{row.fromSku}})
                  </template>
                  <template v-else>
                    {{row.fromGoodsId}}{{row.fromSku ? `(${row.fromSku})` : ''}}
                  </template>
                </template>
              </el-table-column>
              <m-l-code-column prop="fromInventoryId" :label="$t('table.调货MLCode')"></m-l-code-column>
              <template v-if="currentForm.type === 2">
                <el-table-column
                  :label="$t('table.预计从一件代发调出')"
                  align="center"
                  width="200"
                  prop="transferStockNum"
                >
                  <template v-slot="{row}">
                    <template v-if="row.stockBoxInfo.length === 0">-</template>
                    <div
                      v-for="(item,index) in row.stockBoxInfo"
                      :key="index"
                    >
                      {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                    </div>
                  </template>
                </el-table-column>
              </template>

              <el-table-column
                :label="$t('table.预计从中转送仓调出')"
                align="center"
                width="200"
                prop="transferMiddleStockNum"
              >
                <template v-slot="{row}">
                  <template v-if="row.middleBoxInfo.length === 0">-</template>

                  <div
                    v-for="(item,index) in row.middleBoxInfo"
                    :key="index"
                  >
                    {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('table.预计调入商品总数量')"
                align="center"
                width="200"
                prop="exTotalGoodsNum"
              >
                <template v-slot="{row}">
                  {{getExTotalGoodsNum(row)}}
                </template>
              </el-table-column>






            </el-table>
          </div>

        </div>

        <div class="remark">
          <h4>{{$t('shipment.step4Text10')}}：</h4>
          <el-input type="textarea" style="width: 1200px" :placeholder="$t('shipment.step4Text11')" v-model="currentForm.remark"></el-input>
        </div>
      </div>

    </div>

    <el-dialog
      :title="$t('transfer.库存调货')"
      :visible.sync="transferGoodsDialog"
      width="1400px"
    >
      <div style="margin-top: -20px">
        <div class="mgb10 font-bold">{{ $t('transfer.请选择填写从哪个库存中调出') }}</div>
        <div class="mgb10">{{ $t('transfer.当前商品可调货库存') }}: {{editTransferData.transferNum}}</div>
        <el-table
          :data="otherGoodsList"
          row-key="id"
          border
          :span-method="objectSpanMethod2"
          v-tableHeight="{bottomOffset: 80}"
          height="100px"
          ref="goodsTableDataFour"
        >
          <el-table-column
            prop="goodsId"
            :label="$t('table.ListingIDAndSKU')"
            align="left"
            min-width="300"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">

              <template v-if="row.isTB">
                {{ $t('shipment.Not labeled') }}
              </template>
              <template v-else-if="row.isSystemLabel">
                {{ $t('shipment.System label') }}（{{row.sku}}）
              </template>
              <template v-else>
                {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
              </template>
            </template>
          </el-table-column>
          <m-l-code-column></m-l-code-column>
          <template v-if="currentForm.type === 2">
            <el-table-column
              :label="$t('table.一件代发库存')"
              align="center"
              width="200"
              prop="stockNum"
            >
              <template v-slot="{row}">
                {{$t('table.num/箱',{num: row.goodsNumInBox})}} × {{row.stockNum}}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.调出代发库存')"
              align="center"
              width="200"
              prop="transferStockNum"
            >
              <template v-slot="{row}">
                <el-input-number
                  :step="1"
                  :precision="0"
                  :min="0"
                  :max="row.stockNum"
                  :disabled="row.stockNum === 0"
                  v-model="row.transferStockNum"
                  @change="changeNum(row)"
                >
                </el-input-number>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            :label="$t('table.中转送仓库存')"
            align="center"
            width="200"
            prop="middleStockNum"
          >
            <template v-slot="{row}">
              {{$t('table.num/箱',{num: row.goodsNumInBox})}} × {{row.middleStockNum}}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.调出中转库存')"
            align="center"
            width="200"
            prop="transferMiddleStockNum"
          >
            <template v-slot="{row}">
              <el-input-number
                :step="1"
                :precision="0"
                :min="0"
                :max="row.middleStockNum"
                :disabled="row.middleStockNum === 0 || (row.suitListId === editTransferData.id && currentForm.type === 2)"
                v-model="row.transferMiddleStockNum"
                @change="changeNum(row)"
              >
              </el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transferGoodsDialog = false">{{$t('common.cancel')}}</el-button>
        <el-button type="primary" @click="addGoodsData">{{$t('common.confirm')}}</el-button>
      </div>
    </el-dialog>

    <div class="footer">
      <template v-if="step === 1">
        <el-button @click="back">{{$t('common.back')}}</el-button>
      </template>
      <template v-if="step !== 1">
        <el-button @click="prev">{{$t('common.prev')}}</el-button>
      </template>
      <template v-if="step !== 2">
        <el-button @click="nextStep" type="primary">{{$t('shipment.next')}}</el-button>
      </template>
      <template v-else>

        <el-button type="primary" @click="submitWorkData" :loading="btnLoading">{{$t('common.confirm')}}</el-button>

      </template>
    </div>
  </div>
</template>

<script>
import {
  calTransferFee,
  getAllAccountList,
  getTransferGoodsList,
  saveTransferWorkOrder
} from "@/api/transferWork";
import {deepCopy} from "@/utils";
import {jumpLabelOrderInfo, jumpMiddleInfo, jumpTransferInfo} from "@/utils/jumpView";
import {getTransferTypeStr} from "@/utils/transferWork";
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import {EventBus, rechargeTips, rechargeTipsCode} from "@/utils/eventBus";

export default {
  name: "addTransfer",
  components: {MLCodeColumn},
  computed:{
    // 当前的店铺列表
    currentAccountList(){
      return this.allAccountList.map(item => {
        // item.goodsNum = this.currentForm.type === 1 ? item.warehouseGoodsNum : item.fullGoodsNum
        return item
      })
    },
    // sku种数
    currentSkuNum(){
      const set = new Set()
      this.currentGoodsList.forEach(item=>{
        set.add(item.suitId)
      })
      return set.size
    },
    // 商品总数量
    currentGoodsNum(){
      return this.currentGoodsList.reduce((prev,cur)=>{
        let num1 = this.calGoodsNum(cur.stockBoxInfo)
        let num2 = this.calGoodsNum(cur.middleBoxInfo)
        return prev + num1 + num2
      },0)
    },
    // 显示的调货表格数据
    otherGoodsList(){
      return this.editTransferData.otherGoods.filter(item=>{
        return true
      })
    },
    // 计算总的贴标商品数
    exLabelGoodsNum(){
      return this.distributionGoodsListV2.reduce((pre,cur)=>{
        let num1 = this.calGoodsNum(cur.stockBoxInfo)
        let num2 = this.calGoodsNum(cur.middleBoxInfo)
        return pre + num1 + num2;
      },0)
    },
    // 计算调货费用
    exTransferFee(){
      return this.transferFee * this.currentGoodsNum
    },
    // 计算预计总贴标费用
    exTotalLabelFee(){
      return this.labelFee * this.exLabelGoodsNum
    },
    // 计算总费用
    exTotalFee(){
      return this.calTransferFee + this.calLabelFee
    },
    // 无需调货商品数据
    straightGoodsListV2(){
      return this.currentGoodsList.filter(item=>{
        return item.suitListId === item.fromSuitListId
      })
    },
    // 需要调货商品数据
    distributionGoodsListV2(){
      return this.currentGoodsList.filter(item=>{
        return item.suitListId !== item.fromSuitListId
      })
    },
    currentBoxNum(){
      return this.currentGoodsList.reduce((prev,cur)=>{
        let num1 = cur.stockBoxInfo.reduce((last,current)=>{
          return last + current.editNum
        },0)
        let num2 = cur.middleBoxInfo.reduce((last,current)=>{
          return last + current.editNum
        },0)
        return prev + num1 + num2
      },0)
    },
  },
  data(){
    return {
      step: 1,
      currentForm: {
        type: 1, // 类型
        ogAccountId: 0, // 店铺id
        remark: '',
      },
      account: {},
      allAccountList: [],
      labelFee: 0, // 贴标费用
      transferFee: 0, // 调货费用
      loading: false,
      goodsList: [], // 当前请求的商品数据
      goodsLoading: false,
      total: 0,
      goodsParams: {
        page: 1,
        pageSize: 10,
        keyword: '',
      },
      currentGoodsList: [], // 记录有处理过的商品
      editTransferData: { // 修改调货的库存
        otherGoods: [],
      },
      transferGoodsDialog: false,
      straightGoodsList: [], // 无需贴标商品
      distributionGoodsList: [], // 需要贴标商品
      btnLoading: false,
      isSubmit: false,
      calLoading: false, // 计算调货费用loading
      calTransferFee: 0, // 接口计算的调货费用
      calLabelFee: 0, // 接口计算的贴标费用
    }
  },
  created() {
    this.getAllAccountList()
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['goodsTableDataOne'].doLayout();
      this.$refs['goodsTableDataTwo'].doLayout();
      this.$refs['goodsTableDataThree'].doLayout();
      this.$refs['goodsTableDataFour'].doLayout();
    })
  },
  methods: {
    getTransferTypeStr,
    // 获取用户的所有店铺
    getAllAccountList(){
      this.loading = true
      getAllAccountList()
        .then(res=>{
          this.loading = false
          this.allAccountList = deepCopy(res.data)
          if(this.allAccountList.length > 0){
            this.chooseAccount(this.allAccountList[0])
            this.currentForm.ogAccountId = this.allAccountList[0].accountId
            this.account = this.allAccountList[0]
          }
          this.transferFee = res.info.transferFee
          this.labelFee = res.info.labelFee
        })
    },
    changeType(type){
      if(this.currentForm.type === type){
        return
      }
      const haveGoods = this.currentGoodsList.length > 0
      if(haveGoods){
        this.$warning(this.$t('transfer.切换之后已编辑的数据将被清除'), {
          title: this.$t('transfer.确定切换类型或店铺？'),
        })
          .then(res=>{
            // 点击了确定
            this.changeTypeStep2(type)
          })
          .catch(res=>{
            // 点击了取消

          });
      }else{
        this.changeTypeStep2(type)
      }
    },
    changeTypeStep2(type){
      this.currentForm.type = type
      this.currentGoodsList = []
      this.getGoods()
    },
    // 选择店铺
    chooseAccount(account){
      if(this.currentForm.ogAccountId === account.accountId){
        return;
      }
      const haveGoods = this.currentGoodsList.length > 0
      if(haveGoods){
        this.$warning(this.$t('transfer.切换之后已编辑的数据将被清除'), {
          title: this.$t('transfer.确定切换类型或店铺？'),
        })
          .then(res=>{
            // 点击了确定
            this.chooseAccountStep2(account)
          })
          .catch(res=>{
            // 点击了取消

          });
      }else{
        this.chooseAccountStep2(account)
      }
    },
    chooseAccountStep2(account){
      this.goodsParams.page = 1
      this.currentGoodsList = []
      this.currentForm.ogAccountId = account.accountId
      this.account = account
      this.getGoods()
    },
    // 返回上一页
    back(){
      this.$router.go(-1)
    },
    // 下一步
    nextStep(){
      if(this.step === 1){
        if(this.currentGoodsList.length <= 0){
          this.$errorMessage(this.$t('transfer.请至少选择一个商品进行调货'))
          return
        }
        // this.createFinishGoodsData()
        this.calTransferFeeApi()
      }
      this.step++
    },
    calTransferFeeApi(){
      this.calLoading = true
      const boxInfo = this.currentGoodsList.map(item=>{
        const obj = {
          suitId: item.suitId,
          suitListId: item.suitListId,
          middleBoxInfo: item.middleBoxInfo,
          stockBoxInfo: item.stockBoxInfo,
        }
        return obj
      });
      const postData = {
        boxInfo: boxInfo,
        stickerNum: this.exLabelGoodsNum,
        ogAccountId: this.currentForm.ogAccountId,
      }
      calTransferFee(postData)
        .then(res=>{
          this.calLoading = false
          this.calTransferFee = res.data.transferFee
          this.calLabelFee = res.data.labelFee
        })
    },
    // 上一步
    prev(){
      this.step--
    },
    getGoods(){
      const params = deepCopy(this.goodsParams)
      params.ogAccountId = this.currentForm.ogAccountId
      params.type = this.currentForm.type
      this.goodsLoading = true
      getTransferGoodsList(params)
        .then(res=>{
          this.goodsLoading = false
          this.goodsList = res.data.map(item=>{
            item.otherGoods.forEach(goods=>{
              goods.transferMiddleStockNum = 0;
              goods.transferStockNum = 0;
            })
            return item
          })


          this.total = res.info.total
        })
    },
    searchGoods(){
      this.goodsParams.page = 1
      this.getGoods()
    },
    // 修改调货的库存
    editTransferNum(row){
      this.transferGoodsDialog = true
      this.editTransferData = deepCopy(row)
      this.editTransferData.otherGoods.forEach(item=>{
        const findItem = this.currentGoodsList.find(_item=> {
          return _item.id === this.editTransferData.id && item.suitListId === _item.fromSuitListId && item.isTB === _item.fromIsTB && item.isSystemLabel === _item.fromIsSystemLabel
        })
        if(findItem){
          findItem.stockBoxInfo.some(boxItem=>{
            if(boxItem.goodsNumInBox === item.goodsNumInBox){
              item.transferStockNum = boxItem.editNum
              return true;
            }else{
              return false;
            }
          })
          findItem.middleBoxInfo.some(boxItem=>{
            if(boxItem.goodsNumInBox === item.goodsNumInBox){
              item.transferMiddleStockNum = boxItem.editNum
              return true;
            }else{
              return false;
            }
          })
        }
      })
    },
    changeNum(row){
      // 如果填写是空 则设置为0
      if(row.transferStockNum === undefined){
        row.transferStockNum = 0
      }
      if(row.transferMiddleStockNum === undefined){
        row.transferMiddleStockNum = 0
      }

    },
    // 确认添加商品数据
    addGoodsData(){


      // 判断是否新增
      const add = this.otherGoodsList.some(item =>{
        return item.transferStockNum > 0 || item.transferMiddleStockNum > 0
      })
      if(add){
        const copyCurrentGoodsList = this.currentGoodsList.filter(item => item.id !== this.editTransferData.id)
          .map(item=> item)
        const obj = {
          id: this.editTransferData.id,
          accountType: this.editTransferData.accountType,
          attributes: this.editTransferData.attributes,
          goodsId: this.editTransferData.goodsId,
          image: this.editTransferData.image,
          inventoryId: this.editTransferData.inventoryId,
          sku: this.editTransferData.sku,
          suitId: this.editTransferData.suitId,
          suitListId: this.editTransferData.suitListId,
          title: this.editTransferData.title,
          variationId: this.editTransferData.variationId,
          stockNum: this.editTransferData.stockNum,
          middleStockNum: this.editTransferData.middleStockNum
        }
        const obj2 = {};
        let check = this.otherGoodsList.every(item=>{
          if(item.transferMiddleStockNum > 0 || item.transferStockNum > 0){
            const key = item.isTB ? 'TB' : (item.isSystemLabel ? 'SYSTEM' : item.suitListId)
            if(!obj2[key]){
              obj2[key] = []
            }
            obj2[key].push({
              goodsNumInBox: item.goodsNumInBox,
              transferMiddleStockNum: item.transferMiddleStockNum,
              transferStockNum: item.transferStockNum,
            })
            const maxStockNum = item.stockNum // 一件代发的箱子数
            const maxMiddleStockNum = item.middleStockNum // 中转最多的箱子数
            let currentStockNum = item.transferStockNum // 当前的箱子数
            let currentMiddleStockNum = item.transferMiddleStockNum // 当前的箱子数

            copyCurrentGoodsList.forEach(choose=>{
              if(choose.fromSuitId === item.suitId && choose.fromIsTB === item.isTB && choose.fromSuitListId === item.suitListId && choose.fromIsSystemLabel === item.isSystemLabel){
                currentStockNum = choose.stockBoxInfo.filter(boxItem=> boxItem.goodsNumInBox === item.goodsNumInBox)
                  .reduce((prev,boxItem)=>{
                    return prev + boxItem.editNum
                  },currentStockNum)
              }
              if(choose.fromSuitId === item.suitId && choose.fromIsTB === item.isTB && choose.fromSuitListId === item.suitListId && choose.fromIsSystemLabel === item.isSystemLabel){
                currentMiddleStockNum = choose.middleBoxInfo.filter(boxItem=> boxItem.goodsNumInBox === item.goodsNumInBox)
                  .reduce((prev,boxItem)=>{
                    return prev + boxItem.editNum
                  },currentMiddleStockNum)
              }
            })

            if(currentMiddleStockNum > maxMiddleStockNum){
              this.$errorMessage(item.sku+ ":" + item.goodsNumInBox + '/箱，中转库存箱子数量超出库存');
              return false
            }
            if(currentStockNum > maxStockNum){
              this.$errorMessage(item.sku+ ":" + item.goodsNumInBox + '/箱，一件代发数量超出库存');
              return false
            }

          }

          return true
        })
        if(!check){
          return;
        }
        for (const fromSuitListId in obj2) {
          let goodsItem = {}
          if(fromSuitListId === 'TB'){
            goodsItem = this.otherGoodsList.find(item => item.isTB)
          }else if(fromSuitListId === 'SYSTEM'){
            goodsItem = this.otherGoodsList.find(item=> item.isSystemLabel)
          }else{
            goodsItem = this.otherGoodsList.find(item=> item.suitListId === Number(fromSuitListId))
          }
          obj.fromSuitId = goodsItem.suitId
          obj.fromSuitListId = goodsItem.suitListId
          obj.fromGoodsId = goodsItem.goodsId
          obj.fromSku = goodsItem.sku
          obj.fromInventoryId = goodsItem.inventoryId
          obj.fromIsTB = goodsItem.isTB
          obj.fromIsSystemLabel = goodsItem.isSystemLabel
          obj.fromVariationId = goodsItem.variationId
          obj.stockBoxInfo = obj2[fromSuitListId].filter(item => item.transferStockNum > 0)
            .map(item=>{
              return {
                editNum: item.transferStockNum,
                goodsNumInBox: item.goodsNumInBox,
              }
            })
          obj.middleBoxInfo = obj2[fromSuitListId].filter(item => item.transferMiddleStockNum > 0)
            .map(item=>{
              return {
                editNum: item.transferMiddleStockNum,
                goodsNumInBox: item.goodsNumInBox,
              }
            })
          copyCurrentGoodsList.push(deepCopy(obj))

        }
        this.currentGoodsList = copyCurrentGoodsList
      }else{
        this.currentGoodsList = this.currentGoodsList.filter(item => item.id !== this.editTransferData.id)
          .map(item=> item)
      }


      this.transferGoodsDialog = false
    },
    // 判断数据是不是在操作数据中
    isInEditGoodsList(row){
      return this.currentGoodsList.findIndex(item => item.id === row.id) !== -1
    },
    // 根据当前选择的商品 生成对应的商品数据
    createFinishGoodsData(){
      // 先清空数据
      this.straightGoodsList = []
      this.distributionGoodsList = []

      this.currentGoodsList.forEach(item => {
        // 当前这个商品的属性
        const obj = deepCopy(item)
        delete obj.otherGoods

        const otherGoods = deepCopy(item.otherGoods)
        // 先排序数据 把商品数据放在前面非商品数据放在后面
        otherGoods.sort(otherGoods => otherGoods.isGoods ? -1 : (otherGoods.isSystem ? 0 : 1)).forEach(otherGoods => {
          if(!(otherGoods.transferMiddleStockNum > 0 || otherGoods.transferStockNum > 0)){
            return
          }
          const newObj = deepCopy(obj);
          newObj.fromId = otherGoods.id;
          newObj.fromIsGoods = otherGoods.isGoods;
          newObj.fromIsSystem = otherGoods.isSystem;
          newObj.fromIsTB = otherGoods.isTB;
          newObj.transferStockNum = otherGoods.transferStockNum; // 需要调货一件代发库存
          newObj.transferMiddleStockNum = otherGoods.transferMiddleStockNum; // 需要调货中转库存
          newObj.fromMiddleStockNum = otherGoods.middleStockNum
          newObj.fromStockNum = otherGoods.stockNum
          newObj.fromOgAccountId = otherGoods.ogAccountId
          newObj.fromSuitId = otherGoods.suitId
          newObj.fromSuitListId = otherGoods.suitListId
          newObj.fromGoodsId = otherGoods.goodsId
          newObj.fromVariationId = otherGoods.variationId
          newObj.fromSku = otherGoods.sku
          newObj.fromInventoryId = otherGoods.inventoryId

          // 同一个商品不需要贴标 不同商品需要贴标处理
          if(otherGoods.suitListId === item.suitListId){
            this.straightGoodsList.push(newObj)
          }else{
            this.distributionGoodsList.push(newObj)
          }
        })
      })
    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell1()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell1(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'goodsId',
        'stockNum',
        'inventoryId',
        'middleStockNum',
        'exTotalGoodsNum'
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.distributionGoodsListV2.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item.id && item.id === this.distributionGoodsListV2[index - 1].id){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    objectSpanMethod2({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell2()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell2(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'goodsId',
        'inventoryId',
        'exTotalGoodsNum'
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.otherGoodsList.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(
          (item.suitListId && item.suitListId === this.otherGoodsList[index - 1].suitListId) ||
          (item.isSystemLabel && item.isSystemLabel === this.otherGoodsList[index - 1].isSystemLabel) ||
          (item.isTB && item.isTB === this.otherGoodsList[index - 1].isTB)
        ){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 预计调入商品总数量
    getExTotalGoodsNum(row){
      return this.distributionGoodsListV2.filter(goods => goods.id === row.id)
        .reduce((prev,cur)=>{
          return prev + this.calGoodsNum(cur.stockBoxInfo) + this.calGoodsNum(cur.middleBoxInfo)
        },0)
    },
    submitWorkData(){
      const postData = deepCopy(this.currentForm)
      postData.straightGoodsList = this.straightGoodsListV2; //
      postData.distributionGoodsList = this.distributionGoodsListV2
      postData.boxNum = this.currentBoxNum

      this.btnLoading = true
      saveTransferWorkOrder(postData)
        .then(res=>{
          this.isSubmit = true
          this.btnLoading =false
          if(res.error === rechargeTipsCode){
            EventBus.$emit(rechargeTips)
            return;
          }

          if(res.error === 0){
            this.$successMessage(this.$t('common.successful'))
            if(res.data.labelOrderId){
              jumpLabelOrderInfo(res.data.labelOrderId)
            }else{
              jumpTransferInfo(res.data.id)
            }

          }else{
            this.$errorMessage(res.message)
          }
        })
        .catch(res=>{
          this.btnLoading = false
        })

    },
    // 计算商品数量
    calGoodsNum(arr){
      return arr.reduce((prev,cur)=>{
        return prev + cur.editNum * cur.goodsNumInBox
      },0)
    }
  },
  beforeRouteLeave(to,from,next){
    if(this.step > 1 && !this.isSubmit){
      setTimeout(()=>{
        this.$warning(this.$t('shipment.exitPageText2'),{
          title: this.$t('shipment.exitPageTitle'),
        }).then(()=>{
          next();
        }).catch(() => {
          next(false);
        })
      },0)
    }else{
      next()
    }
  },
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 20px 30px;

  .header {
    display: flex;
    justify-content: space-between;
  }

  .content {
    padding: 0px 0 0;
  }



  .step-tips{
    margin-top: 10px;
    font-size: 12px;
    color: #AAAAAA;
  }

  .step-content{
    .account-list{
      .haveGoodsButton{
        color: #67C23A;
        border-color: #67C23A;
        background-color: #f0f9eb;
      }
    }
    .goods-table{
      margin-top: 20px;
    }
    .box-card{
      background-color: #f2f2f2;
      font-weight: 500;
      .line{
        display: flex;
        font-size: 14px;
        margin-bottom: 10px;
      }
    }

  }

  .footer{
    margin-top: 30px;
  }

}
</style>
